'''
燃动力”运动意外伤害保险
'''
import sys

sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests, json
from pyquery import PyQuery as pq
from urllib.parse import urlencode
from common.helper import Helper


class Spider(object):

    def __init__(self):

        self.mysql = MysqlClient()

        self.name = "燃动力”运动意外伤害保险"

    # 生成产品数据
    def genProductInfo(self):

        #生成数据
        plan  = {

            "planA":{

                # 使用年龄范围
                "year":["3~65"],
                # 运动项目
                "spitem":self.getSportLevel(),
                # 保险期限 30 60 90 120 180 210 240 270 300 330 360 / 天
                "expire":[str(i) for i in range(30,390,30)],
                # 介绍
                "introduce":{

                    "运动意外身故/残疾保险金": "10 万",
                    "运动意外医疗保险金": "1 万",
                    "运动中猝死保险金": "10 万"
                }


            },
            "planB": {

                # 使用年龄范围
                "year": ["3~65"],
                # 运动项目
                "spitem": self.getSportLevel(),
                # 保险期限 30 60 90 120 180 210 240 270 300 330 360 / 天
                "expire": [str(i) for i in range(30, 390, 30)],
                # 介绍
                "introduce": {

                    "运动意外身故/残疾保险金": "20 万",
                    "运动意外医疗保险金": "2 万",
                    "运动中猝死保险金": "20 万"
                }

            },
            "planC": {

                # 使用年龄范围
                "year": ["3~65"],
                # 运动项目
                "spitem": self.getSportLevel(),
                # 保险期限 30 60 90 120 180 210 240 270 300 330 360  /天
                "expire": [str(i) for i in range(30, 390, 30)],
                # 介绍
                "introduce": {

                    "运动意外身故/残疾保险金": "50 万",
                    "运动意外医疗保险金": "2 万",
                    "运动中猝死保险金": "50 万"
                }

            }

        }

        for k in plan:

            planCode = k

            for v in product( plan[planCode]["year"],plan[planCode]["spitem"],plan[planCode]["expire"] ):

                # 运动系数等级
                sport = '{0}'.format( plan[planCode]["spitem"][v[1]])

                # 方案介绍
                introduce = "'" + json.dumps( plan[planCode]["introduce"],ensure_ascii=False) + "'"

                self.mysql.cursor.execute( domain[self.name]["insert_sql"].format( planCode,v[0],v[1],sport,v[2],introduce  ) )

                self.mysql._conn.commit()

                print( "%s产品信息写入数据库成功"%self.name )



    # 获取运动等级
    def getSportLevel(self, url="https://www.cpic.com.cn/market/c/2019-05-17/1575777.shtml?SCsite=healthLb"):

        header = {

            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.79 Safari/537.36"
        }

        r = lambda: requests.get(url, headers=header)

        if r().status_code == 200:

            text = r().text.encode('ISO-8859-1').decode(

            requests.utils.get_encodings_from_content(r().text)[0]);

        doc = pq(text)

        items = doc(".sport-block .sports-items dd ").items()

        # 定义运动列表
        # A项目运动列表
        Asport = []
        # B项目运动列表
        Bsport = []
        # C项目运动列表
        Csport = []

        for item in items:

            # A运动归类
            if item.attr("aria-level") == "A":

                Asport.append( item.text( ))

            # B运动归类
            elif item.attr("aria-level") == "B":

                Bsport.append(item.text())

            # C运动归类
            else:

                Csport.append(item.text())

        data = {

            "A":Asport,
            "B":Bsport,
            "C":Csport
        }
        return data

    #执行爬虫
    def requestJson(self,dt=None):


        dt = {

            "plan":"planA",
            "level":"A",
            "expire":"30"


        }
        data = {

            "productCode": "81080100",
            "plan": dt["plan"],
            "itemCode": dt["level"],
            "startDate": "2019-12-26",
            "endDate": self.filterDate( dt["expire"])
        }

        r = requests.post( url = domain[self.name]["url"],headers=domain[self.name]["header"],data=urlencode( data).replace('+',''))

        print( r.text )

        if r.status_code == 200 and r.json()["resultCode"] == "1":

            price = Helper.decimalParse( r.json()["premium"])

            data = {

                "name":self.name,
                "price":price,
                "id":dt["id"]
            }
            # self.mysql.updatePrice( data )

        else:

            data = {

                "name":self.name,
                "id":dt["id"],
                "state":3
            }

            # self.mysql.updateTask( data )

    def main(self):

        while True:

            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)

            if not dt:
                print("产品价格抓取完成~~~")

                return

                # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            self.mysql.updateTask(data)

            self.requestJson(dt)

    # 过滤日期
    def filterDate(self,day=None):

        date = {
            "30":"2020-01-26",

            "60": "2020-02-26",

            "90": "2020-03-26",

            "120": "2020-04-26",

            "150": "2020-05-26",

            "180": "2020-06-26",

            "210": "2020-07-26",

            "240": "2020-08-26",

            "270": "2020-09-26",

            "300": "2020-10-26",

            "330": "2020-11-26",

            "360": "2020-12-26",

        }

        return date[day]
